package org.quickbundle.project.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.dfhc.util.StringHelper;

public class FilterXss implements Filter {
	public FilterConfig config;

	/**
	 * 解决XSS注入问题
	 * 
	 * @param msg
	 * @return
	 */
	public boolean isContains(String container, String[] regx) {
		boolean result = false;
		for (int i = 0; i < regx.length; i++) {
			if (StringHelper.isEmpty(regx[i].trim())) {
				continue;
			}
			if (container.indexOf(regx[i].trim()) != -1) {
				return true;
			}
		}
		return result;
	}

	public void doFilter(ServletRequest servletrequest,
			ServletResponse servletresponse, FilterChain filterchain)
			throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest) servletrequest;
		String filterStrings = config.getInitParameter("filterStrings");// 需要忽略过滤的
		String[] filterList = filterStrings.split(";");
		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
				(HttpServletRequest) servletrequest);
		if (this.isContains(hrequest.getRequestURI(), filterList)) {// 不用对进行过滤
			filterchain.doFilter(servletrequest, servletresponse);
		} else {
			filterchain.doFilter(xssRequest, servletresponse);// 对进行过滤
		}
	}

	public void init(FilterConfig filterconfig) throws ServletException {
		// TODO Auto-generated method stub
		config = filterconfig;

	}

	public void destroy() {
		// TODO Auto-generated method stub
		config = null;

	}

}
